import type { Module, ActionContext } from 'vuex'
import type { AxiosResponse } from 'axios'
import type { hardwareState } from './typings'
import {
  hardwareListGet,
  hardwareRemovePost,
  hardwareExportGet,
  hardwareImportExcelGet,
  hardwareModelGet,
  hardwareViewGet,
  hardwareAddPost,
  hardwareUpdatePost,
  hardwareExportTemplateGet
} from '~/api/asset/hardware'
import { DownloadAttachment } from '~/utils/util'

const hardware: Module<hardwareState, hardwareState> = {
  namespaced: true,
  state: {
    hardwareModelOpt: []
  },
  getters: {
    hardwareModelOpt: (state) => state.hardwareModelOpt
  },
  mutations: {
    SET_HARDWARE_MODEL: (state, payload) => {
      state.hardwareModelOpt = payload
    }
  },
  actions: {
    // 回路监控箱-型号
    async HardwareModelGet<S, T>({ commit }: ActionContext<S, T>) {
      return await hardwareModelGet({}).then((res: AxiosResponse) => {
        commit('SET_HARDWARE_MODEL', res?.data?.data || [])
        return res?.data
      })
    },
    // 回路监控箱-列表
    async HardwareListGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareListGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 回路监控箱-删除
    async HardwareRemovePost<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareRemovePost<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 回路监控箱-导出
    async HardwareExportGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareExportGet<T>(params).then((res: AxiosResponse) => {
        const contentDisposition = res?.headers?.['content-disposition']
        if (contentDisposition && res.data) {
          DownloadAttachment(decodeURI(contentDisposition.substring(20)), res.data)
        }
        return res.data
      })
    },
    // 回路监控箱-模版下载
    async HardwareExportTemplateGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareExportTemplateGet<T>(params).then((res: AxiosResponse) => {
        const contentDisposition = res?.headers?.['content-disposition']
        if (contentDisposition && res.data) {
          DownloadAttachment(decodeURI(contentDisposition.substring(20)), res.data)
        }
        return res.data
      })
    },
    // 回路监控箱-导入
    async HardwareImportExcelGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareImportExcelGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 回路监控箱-详情
    async HardwareViewGet<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareViewGet<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 回路监控箱-新增
    async HardwareAddPost<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareAddPost<T>(params).then((res: AxiosResponse) => res?.data)
    },
    // 回路监控箱-修改
    async HardwareUpdatePost<S, T>(_: ActionContext<S, T>, params: T) {
      return await hardwareUpdatePost<T>(params).then((res: AxiosResponse) => res?.data)
    }
  }
}

export default hardware
